package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报表管理
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;
    @Reference
    private OrderService orderService;

    @RequestMapping("/getAgeReport")
    public Result getAgeReport() throws ParseException {
        try {
            List<Integer> agegroupCount = memberService.findAgegroupCount();
            return new Result(true,"查询年龄段数据成功",agegroupCount);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询年龄段数据失败");
        }

    }

    @RequestMapping("/getIncomeReport")
    public Result getIncomeReport(String[] checkedTime) throws ParseException {
        //声明一个map集合根据键值对形式放入map中
        Map<String, Object> map = new HashMap<>();
        //声明一个集合用来封装计算好的月份日期
        List<String> dates = new ArrayList<>();

        String startDates = null;
        String endDates = null;
        if (checkedTime == null) {
            Calendar calendar = Calendar.getInstance();//获取日历对象
            calendar.add(Calendar.DATE, -12);
            //计算过去一年12天日期
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.DATE, 1);
                Date time = calendar.getTime();
                //将产生的月份按照设置好的格式放入集合中
                dates.add(new SimpleDateFormat("yyyy-MM-dd").format(time));

                if (i==0){
                    startDates = new SimpleDateFormat("yyyy-MM-dd").format(time);
                }
                if (i==11){
                    endDates = new SimpleDateFormat("yyyy-MM-dd").format(time);
                }
            }

            map.put("dates", dates);
        } else {
            startDates = checkedTime[0];
            endDates = checkedTime[1];
            dates.add(startDates);
            dates.add(endDates);
            map.put("dates", dates);
        }
        //查询所有套餐
        List<String> setmealName = setmealService.findAllSetmeal();
        map.put("setmealName", setmealName);
        //查询所有收入与套餐对应
        List<Map<String,Object>> income = reportService.findIncomeByDate(startDates,endDates);
        map.put("income", income);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }


    @RequestMapping("/getOrderReport")
    public Result getOrderReport(String[] checkedTime) throws ParseException {
        System.out.println(checkedTime);
        //声明一个map集合根据键值对形式放入map中
        Map<String, Object> map = new HashMap<>();
        //声明一个集合用来封装计算好的月份日期
        List<String> dates = new ArrayList<>();

        if(checkedTime == null){
            Calendar calendar = Calendar.getInstance();//获取日历对象
            calendar.add(Calendar.DATE, -12);
            //计算过去一年12天日期
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.DATE, 1);
                Date time = calendar.getTime();
                //将产生的月份按照设置好的格式放入集合中
                dates.add(new SimpleDateFormat("yyyy-MM-dd").format(time));
            }
            map.put("dates", dates);
        }else{
            String startDates = checkedTime[0];
            String endDates = checkedTime[1];

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Calendar calendar = new GregorianCalendar();
            dates.add(startDates);
            while (!startDates.equals(endDates)){
                Date d = sdf.parse(startDates);
                calendar.setTime(d);
                calendar.add(calendar.DATE,1);
                d=calendar.getTime();   //这个时间就是日期往后推一天的结果
                startDates = sdf.format(d);
                dates.add(startDates);
            }
            map.put("dates", dates);
        }

        //调用业务层进行业务操作
        List<Integer> orderCount = orderService.findDayOrderCount(dates);
        map.put("orderCount", orderCount);
        //调用业务层进行业务操作
        List<Integer> visitCount = orderService.findDayVisitCount(dates);
        map.put("visitCount", visitCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }


    //    会员折线图数据查询
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        //"months":["2019.01","2019.02","2019.03","2019.04"],
        // "memberCount":[3,4,8,10]
        Calendar calendar = Calendar.getInstance();//获取日历对象
        calendar.add(Calendar.MONTH, -12);//向前推12个月
        //声明一个集合用来封装计算好的月份日期
        List<String> months = new ArrayList<>();
        //声明一个map集合根据键值对形式放入map中
        Map<String, Object> map = new HashMap<>();
        //向后推一个月
        //计算过去一年12个月份日期
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date time = calendar.getTime();
            //将产生的月份按照设置好的格式放入集合中
            months.add(new SimpleDateFormat("yyyy-MM").format(time));
        }
        map.put("months", months);
        //调用业务层进行业务操作
        List<Integer> membercount = memberService.findMonthCount(months);
        map.put("memberCount", membercount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    //查询套餐预约占比的数据
    //" setmealNames":['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
    // "setmealCount":[
    //                 {value: 335, name: '直接访问'},
    //                {value: 310, name: '邮件营销'},
    //                {value: 234, name: '联盟广告'},
    //                {value: 135, name: '视频广告'},
    //                {value: 1548, name: '搜索引擎'}]
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        //调用业务层查询数据
        List<Map<String, Object>> list = setmealService.findByName();
        Map map = new HashMap<>();
        //将查询到数据放入map集合中
        map.put("setmealCount", list);
        if (list != null && list.size() > 0) {
            for (Map<String, Object> m : list) {
                String name = (String) m.get("name");
                map.put("name", name);
            }
        }
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    //运营数据统计查询
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> data = reportService.findMemberAndOrder();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //将数据写入到excel中
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = reportService.findMemberAndOrder();
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //获取文件的绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //根据模板文件创建一个excel表格
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //获取第一个工作表内容
            XSSFSheet sheet = excel.getSheetAt(0);
            //设置时间日期
            XSSFRow daterow = sheet.getRow(2);
            XSSFCell datecell = daterow.getCell(5);
            datecell.setCellValue(reportDate);
            //设置新增会员数
            XSSFRow membercountrow = sheet.getRow(4);
            XSSFCell membercell = membercountrow.getCell(5);
            membercell.setCellValue(todayNewMember);
            //总会员数
            XSSFRow totalMemberRow = sheet.getRow(4);
            XSSFCell totalMemberCell = totalMemberRow.getCell(7);
            totalMemberCell.setCellValue(totalMember);
            //本周新增会员数
            XSSFRow MondayMemberRow = sheet.getRow(5);
            XSSFCell MondayMemberCell = MondayMemberRow.getCell(5);
            MondayMemberCell.setCellValue(thisWeekNewMember);
            //本月新增会员数
            XSSFRow MonthMemberRow = sheet.getRow(5);
            XSSFCell monthMemberCell = MonthMemberRow.getCell(7);
            monthMemberCell.setCellValue(thisMonthNewMember);
            //今日预约数
            XSSFRow todayOrderRow = sheet.getRow(7);
            XSSFCell todayOrderCell = todayOrderRow.getCell(5);
            todayOrderCell.setCellValue(todayOrderNumber);
            //今日到诊数
            XSSFRow todayvisitsRow = sheet.getRow(7);
            XSSFCell todayvisitsCell = todayvisitsRow.getCell(7);
            todayvisitsCell.setCellValue(todayVisitsNumber);
            //本周预约数
            XSSFRow MondayOrderRow = sheet.getRow(8);
            XSSFCell MondayOrderCell = MondayOrderRow.getCell(5);
            MondayOrderCell.setCellValue(thisWeekOrderNumber);
            //本周到诊数
            XSSFRow MondayVisitsRow = sheet.getRow(8);
            XSSFCell MondayVisitsCell = MondayVisitsRow.getCell(7);
            MondayVisitsCell.setCellValue(thisWeekVisitsNumber);
            //本月预约数
            XSSFRow MonthOrderRow = sheet.getRow(9);
            XSSFCell MonthOrderCell = MonthOrderRow.getCell(5);
            MonthOrderCell.setCellValue(thisMonthOrderNumber);
            //本月到诊数
            XSSFRow MonthVisitsRow = sheet.getRow(9);
            XSSFCell MonthVisitsCell = MonthVisitsRow.getCell(7);
            MonthVisitsCell.setCellValue(thisMonthVisitsNumber);
            int rowNum = 12;
            for (Map map : hotSetmeal) {
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                XSSFRow row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue((String) map.get("name"));//套餐名称
                row.getCell(5).setCellValue((Long) map.get("setmeal_count")); //预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());  //占比
            }
            //使用输出流进行表格下载，基于了浏览器客户端
            ServletOutputStream outputStream = response.getOutputStream();
            //设置响应类型，指定为excel类型
            response.setContentType("application/vnd.ms-excel");
            //设置响应头，以附件形式下载
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            //将文件写出
            excel.write(outputStream);
            outputStream.flush();
            outputStream.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.UPLOAD_FAIL);
        }
    }
    //将数据写入到pdf中
    @RequestMapping("/exportBusinessReportPdf")
    public Result exportBusinessReportPdf(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = reportService.findMemberAndOrder();
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //获取模板的绝对路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
            //填充数据
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,result, new JRBeanCollectionDataSource(hotSetmeal));
            //使用输出流进行表格下载，基于了浏览器客户端
            ServletOutputStream outputStream = response.getOutputStream();
            //设置响应类型，指定为pdf类型
            response.setContentType("application/pdf");
            //设置响应头，以附件形式下载
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            //输出
           JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);
           return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.UPLOAD_FAIL);
        }
    }


    @RequestMapping("/getInterfaceReport")
    public Result getInterfaceReportData(String leaveTime) {
        String todayTime = null;
        try {
            todayTime = DateUtils.parseDate2String(DateUtils.getToday());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date s = null;
        if(!leaveTime.equals("today")){
            try {
                s = DateUtils.parseString2Date(leaveTime);
                Date todayDate = DateUtils.parseString2Date(todayTime);

                if(s.after(todayDate)){
                    System.out.println("错了");
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if("today".equals(leaveTime)|| todayTime.equals(leaveTime)){
           try {
                Map<String, Object> data = reportService.InterfaceReportData();
                return new Result(true, "获取接口数据成功", data);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(true, "获取接口数据失败");
            }

        }else {
            try {
                Map<String, Object> data = reportService.InterfaceReportDataFromMysql(leaveTime);
                return new Result(true, "获取接口数据成功", data);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(true, "获取接口数据失败");
            }
        }
    }
}
